#include "comm.h"
#include "mb.h"
#include "host_data_type.h"
#include "thread_manager.h"
#include <math.h>

#define DBG_TAG    "th_comm"
#define DBG_LVL    DBG_INFO
#include <rtdbg.h>

rt_weak void comm_sync(rt_uint16_t *hold_reg_buf)
{
    rt_kprintf("Warning: No Sync function defined\r\n");
}

void comm_notify(rt_uint8_t arg_id, rt_uint16_t arg_value)
{
    struct Msg_InterThread msg;

    msg.arg_id = arg_id;
    msg.arg_value = arg_value;
    rt_mq_send(mq_host, &msg, sizeof(msg));
}

void comm_listen(void)
{
    rt_ssize_t recvState;
    struct Msg_InterThread msg_comm[MSG_MAX_COMM];

    RT_ASSERT(mq_host != RT_NULL);
    recvState = rt_mq_recv(mq_comm, msg_comm, MSG_MAX_COMM * sizeof(struct Msg_InterThread), RT_WAITING_FOREVER);
    if(recvState > 0)
    {
        for(rt_uint8_t i = 0; i < recvState / sizeof(struct Msg_InterThread); i++)
        {
            if(msg_comm[i].arg_id == ARG_ID_PV)
            {
                regInBuf[0] = (rt_uint16_t)(msg_comm[i].arg_value / pow(10, 2 + Decimal_Point_Nbr_0 - regHoldBuf[ARG_ID_DecimalPointNbr]));
            }
            else
            {
                switch(msg_comm[i].arg_id)
                {
                    case ARG_ID_MBBaudrateID:
                        comm_pc_set_baudrate(msg_comm[i].arg_value);
                        break;
                    default:
                        break;
                }
                regHoldBuf[msg_comm[i].arg_id] = (rt_uint16_t)msg_comm[i].arg_value;
                // rt_kprintf("arg_id:%d\t arg_value:%d\n", msg_comm[i].arg_id, msg_comm[i].arg_value);
            }
        }
    }
}

void comm_tx_thread_entry(void *parameter)
{
    while(1)
    {
        comm_listen();
        rt_thread_mdelay(10);
    }
}

void comm_rx_thread_entry(void *parameter)
{
    while(1)
    {
        mb_poll();
        rt_thread_mdelay(10);
    }
}

int comm_thread_init(void)
{
    rt_thread_t tid;
    comm_sync(regHoldBuf);
    mb_init();
    

    tid = rt_thread_create("comm_tx", comm_tx_thread_entry, RT_NULL, 2048, 6, 50);
    if(tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }
    tid = rt_thread_create("comm_rx", comm_rx_thread_entry, RT_NULL, 2048, 6, 50);
    if(tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }
        
    return 0;
}